//
//  EntertainmentViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/13.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "EntertainmentViewController.h"
#import "BigScrollView.h"          //自定义试图
#import "VideoTableViewCell.h"
#import "JokeTableViewCell.h"
#import "VideoModel.h"
#import "JokeModel.h"
#import "UMSocial.h"
#import "MoviePlayerViewController.h"
#define kVideoURL @"http://c.m.163.com/nc/video/list/V9LG4B3A0/y/0-10.html"
#define kJokeURL @"http://m2.qiushibaike.com/article/list/text?count=30&readarticles=%5B111311950%2C111314144%2C111313519%2C111313479%2C111318355%2C111316677%2C107510538%2C111313522%2C111314746%2C107504712%2C111311943%2C111313274%2C111319633%2C111315517%2C107510177%2C111316135%2C111319896%2C111314729%2C111317794%2C107430785%2C107432941%2C107429623%2C107428450%2C107429467%2C107429785%2C107428126%5D&page=1&AdID=143696337021316BA893FA"
@interface EntertainmentViewController () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,MPMoviePlayerControllerDelegate>
{
    CGRect _bounds;    //自适应高度。
    int counts;        //jokeTableView加载页数。
    int pages;         //
}
@property (nonatomic, strong) BigScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, strong) NSMutableArray *jokeArray;
@property (nonatomic, strong) UIImageView *scrollImageView;
@property (nonatomic, strong) UIButton *oneButton;
@property (nonatomic, strong) UIButton *twoButton;
@end

@implementation EntertainmentViewController

- (void)loadView
{
    self.scrollView = [[BigScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    
    self.scrollView.scrollView.delegate = self;
    self.scrollView.jokeTableView.delegate = self;
    self.scrollView.videoTableView.delegate = self;
    self.scrollView.jokeTableView.dataSource = self;
    self.scrollView.videoTableView.dataSource = self;
    
    //下拉刷新
    [self.scrollView.videoTableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(downRequest)];
    //上拉加载
    [self.scrollView.videoTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(videoFooterRereshing)];
    
    //下拉刷新。
    [self.scrollView.jokeTableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(requestJoke)];
    //上拉加载
    [self.scrollView.jokeTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(jokeFooterRereshing)];
    
    self.view = _scrollView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addNavigationView];
    [self downRequest];
    [self requestJoke];
    [self loadNavigationIndfo];
}

#pragma mark - 下拉刷新视频
- (void)downRequest
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网
    if ([r currentReachabilityStatus] != NotReachable)
    {
        [FMDBManage deleteAllVideoTable];   //刷新成功后再移除数据库中数据。
    }
    else
    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
    }
    
    // 解析
    [self requestVideo];
}

#pragma mark - 设置导航栏
- (void)loadNavigationIndfo
{
    //设为不透明
    self.navigationController.navigationBar.translucent = NO;

    
    // 导航栏颜色
    self.navigationController.navigationBar.barTintColor = [UIColor RGBColor:71 green:128 blue:208 alpha:1];
    
    // 标题颜色
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
}

#pragma mark - 下拉刷新段子
- (void)requestJoke
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网
    if ([r currentReachabilityStatus] != NotReachable)
    {
        [FMDBManage deleteAllJokeTable];   //刷新成功后再移除数据库中数据。
    }
    else
    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
    }
    // 重新解析
    [self requestJoke1];
}

#pragma - mark - 顶部滑块试图
- (void)addNavigationView
{
    //背景图片 （层级：背景图->滑块图->按钮）
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth/2 -55, 20)];
    backgroundImageView.userInteractionEnabled = YES;
    self.scrollImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 55, 20)];
    self.scrollImageView.image = [UIImage imageNamed:@"night_channel_grid_circle"];
    [backgroundImageView addSubview:_scrollImageView];
    //第一个Button
    self.oneButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.oneButton.frame = CGRectMake(0, 0, 55, 20);
    [self.oneButton addTarget:self action:@selector(oneButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.oneButton setTitle:@"视屏" forState:UIControlStateNormal];
    [backgroundImageView addSubview:_oneButton];
    //第二个button
    self.twoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.twoButton.frame = CGRectMake(55, 0, 55, 20);
    [self.twoButton addTarget:self action:@selector(twoButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.twoButton setTitle:@"段子" forState:UIControlStateNormal];
    [backgroundImageView addSubview:_twoButton];
    
    self.navigationItem.titleView = backgroundImageView;
    
}
#pragma - mark - 滑块Frame渐变 Button字体颜色渐变
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //问题：滑动TableView时，scrollView的偏移量变成0.
    //分析：tableView是继承scrollView的，当TableView时代理方法可能认为 TableView是这个scrollView 而使偏移量等于0.
    //解决：判断是哪个ScrollView。（多个相同的对象都没调用的方法，用参数和想要调用的做判断）
    if ([scrollView isEqual:_scrollView.scrollView]) {
        //按比例移动小滑块的距离。
        CGFloat x = (55/320.0)*scrollView.contentOffset.x;
        [self scrollViewToTopWithx:x];
        self.scrollImageView.frame = CGRectMake(kScreenWidth / 2 - 160 + x, 0, 55, 20);
        //颜色的渐变计算( 0 -> 255 )
        CGFloat colorValue = (NSInteger)(255/55.0 * x)%256;
        [self.oneButton setTintColor:[UIColor colorWithRed: (255 - colorValue)/255.0 green:(255 - colorValue)/255.0 blue:(255 - colorValue)/255.0 alpha:1]];
        [self.twoButton setTintColor:[UIColor colorWithRed:colorValue/255.0 green:colorValue/255.0 blue:colorValue/255.0 alpha:1]];
    }
}
#pragma - mark - 实现点击状态栏回顶部。
- (void)scrollViewToTopWithx:(CGFloat)x
{
    if (x == 0) {
        self.scrollView.videoTableView.scrollsToTop = YES;
        self.scrollView.jokeTableView.scrollsToTop = NO;
    }else
    {
        self.scrollView.videoTableView.scrollsToTop = NO;
        self.scrollView.jokeTableView.scrollsToTop = YES;
    }
}

- (void)oneButtonAction
{
    [self.scrollView.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)twoButtonAction
{
    [self.scrollView.scrollView setContentOffset:CGPointMake(kScreenWidth, 0) animated:YES];
}

- (void)requestVideo
{
    
    [FMDBManage createVideoTable];
    NSMutableArray *videoArray = [FMDBManage selectAllVideoTable]; // 查询数据库
    
    if (videoArray.count != 0)
    {
        self.videoArray = videoArray;
    }
    else
    {
        [self.videoArray removeAllObjects];          //刷新是先把原先数组清空。
        pages = 10;
        [LORequestManger GET:kVideoURL success:^(id response) {
            NSDictionary *bDic = (NSDictionary *)response;
            NSArray *array = [bDic objectForKey:@"V9LG4B3A0"];
            for (NSDictionary *dic in array) {
                VideoModel *model = [VideoModel videoModelWithDictionary:dic];
                // 插入数据库
                [FMDBManage insertVideoTableTitle:model.title videoTime:[NSString stringWithFormat:@"%ld",(long)model.length] playCount:[NSString stringWithFormat:@"%ld",(long)model.playCount] replyCount:[NSString stringWithFormat:@"%ld",(long)model.replyCount]];
                
                [self.videoArray addObject:model];
            }
            [self.scrollView.videoTableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
    }
    [self.scrollView.videoTableView.header endRefreshing];   //下拉刷新。
}

- (void)requestJoke1
{
    [FMDBManage createJokeTable];
    NSArray * arr = [FMDBManage selectAllJokeTable];
    if (arr.count != 0) {
        self.jokeArray = [arr mutableCopy];
    }
    else
    {
        counts = 30;
        [LORequestManger GET:kJokeURL success:^(id response) {
            NSDictionary *bDic = (NSDictionary *)response;
            [self.jokeArray removeAllObjects];         //刷新时清空数据。
            NSArray *array = [bDic objectForKey:@"items"];
            for (NSDictionary *dic in array) {
                JokeModel *model = [[JokeModel alloc] init];
                model.content = [dic objectForKey:@"content"];
                //判断是否有用户信息。
                if ([[dic objectForKey:@"user"] isEqual:[NSNull null]]) {
                    model.login = @"匿名作者";
                }else{
                NSDictionary *cDic = [dic objectForKey:@"user"];
                    model.login = [cDic objectForKey:@"login"];
                }

                model.up = (int)[[dic objectForKey:@"votes"] objectForKey:@"up"];
                model.down = (int)[[dic objectForKey:@"votes"] objectForKey:@"down"];
                
                [FMDBManage insertJokeTableContent:model.content login:model.login down:[NSString stringWithFormat:@"%ld",model.down] up:[NSString stringWithFormat:@"%ld",model.up]];
                
                [self.jokeArray addObject:model];
            }
            [self.scrollView.jokeTableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭,请检查网络"];
        }];
    }
    [self.scrollView.jokeTableView.header endRefreshing];   //下拉刷新。
}

#pragma - mark - JokeTableView上拉加载 (在url页码上添加东西)
- (void)jokeFooterRereshing
{
    counts += 30;
    NSString *urlStr1 = [NSString stringWithFormat:@"http://m2.qiushibaike.com/article/list/text?count=%d",counts];
    NSString *urlStr2 = [urlStr1 stringByAppendingString:@"&readarticles=%5B111311950%2C111314144%2C111313519%2C111313479%2C111318355%2C111316677%2C107510538%2C111313522%2C111314746%2C107504712%2C111311943%2C111313274%2C111319633%2C111315517%2C107510177%2C111316135%2C111319896%2C111314729%2C111317794%2C107430785%2C107432941%2C107429623%2C107428450%2C107429467%2C107429785%2C107428126%5D&page=1&AdID=143696337021316BA893FA"];
    [LORequestManger GET:urlStr2 success:^(id response) {
        [self.jokeArray removeAllObjects];
        NSDictionary *bDic = (NSDictionary *)response;
        NSArray *array = [bDic objectForKey:@"items"];
        for (NSDictionary *dic in array) {
            JokeModel *model = [[JokeModel alloc] init];
            model.content = [dic objectForKey:@"content"];
            //判断是否有用户信息。
            if ([[dic objectForKey:@"user"] isEqual:[NSNull null]]) {
                model.login = @"匿名作者";
            }else{
                NSDictionary *cDic = [dic objectForKey:@"user"];
                model.login = [cDic objectForKey:@"login"];
            }
            
            model.up = (int)[[dic objectForKey:@"votes"] objectForKey:@"up"];
            model.down = (int)[[dic objectForKey:@"votes"] objectForKey:@"down"];
            [self.jokeArray addObject:model];
        }
        [self.scrollView.jokeTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭,请检查网络"];
    }];
    [self.scrollView.jokeTableView.footer endRefreshing];   //下拉刷新停止。
}

#pragma - mark - videoTableView上拉加载
- (void)videoFooterRereshing
{
    pages += 10;
    NSString *urlStr = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/list/V9LG4B3A0/y/%d-10.html",pages];
    [LORequestManger GET:urlStr success:^(id response) {
        NSDictionary *bDic = (NSDictionary *)response;
        NSArray *array = [bDic objectForKey:@"V9LG4B3A0"];
        for (NSDictionary *dic in array) {
            VideoModel *model = [VideoModel videoModelWithDictionary:dic];
            [self.videoArray addObject:model];
        }
        [self.scrollView.videoTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭,请检查网络"];
    }];
    
    [self.scrollView.videoTableView.footer endRefreshing];   //下拉刷新。
}

#pragma - mark - UITableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_scrollView.videoTableView]) {
        return self.videoArray.count;
    }
    return self.jokeArray.count;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_scrollView.videoTableView]) {
        static NSString *cellIdentifier = @"cell";
        [tableView registerClass:[VideoTableViewCell class] forCellReuseIdentifier:cellIdentifier];
        VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        VideoModel *model = [self.videoArray objectAtIndex:indexPath.row];
        [cell cellSetModel:model];
        
        return cell;
    }else{
        static NSString *cellIdentifier = @"cell1";
        [tableView registerClass:[JokeTableViewCell class] forCellReuseIdentifier:cellIdentifier];
        JokeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        [cell.shareButton addTarget:self action:@selector(shareButton:) forControlEvents:UIControlEventTouchUpInside];
        JokeModel *model = [self.jokeArray objectAtIndex:indexPath.row];
        [cell cellSetModel:model];  //cell赋值
        
        return cell;
    }
}
#pragma - mark - 分享方法。
- (void)shareButton:(UIButton *)button
{
    // 找到cell
    JokeTableViewCell *cell= (JokeTableViewCell *)button.superview.superview;
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"55a8c25567e58e15d8000cb2" shareText:[NSString stringWithFormat:@"%@ \n  ----- 来自IT家园应用！",cell.contentLabel.text] shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent ,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQzone,UMShareToQQ,UMShareToRenren,UMShareToEmail,nil] delegate:nil];
}
#pragma - mark - tableView 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([tableView isEqual:_scrollView.videoTableView]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        MoviePlayerViewController *movieVc = [[MoviePlayerViewController alloc] init];
        movieVc.delegate = self;
        VideoModel *model = [self.videoArray objectAtIndex:indexPath.row];
        movieVc.mp4_url = model.mp4_url;
        [self presentViewController:movieVc animated:YES completion:nil];
    }
}
#pragma - mark - 代理释放自己推出的播发器 谁申请 谁释放
- (void)moviePlayerDidFinished
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma - mark - 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_scrollView.videoTableView]) {
        return 230;
    }
    //JokeTableViewCell自适应高度。
    JokeTableViewCell *cell = [[JokeTableViewCell alloc] init];
    CGRect bounds = [cell heightForCell:[self.jokeArray objectAtIndex:indexPath.row]];
    return bounds.origin.y + bounds.size.height + 45;
}

#pragma - mark - 懒加载
- (NSMutableArray *)videoArray
{
    if (_videoArray == nil) {
        _videoArray = [NSMutableArray array];
    }
    return _videoArray;
}

- (NSMutableArray *)jokeArray
{
    if (_jokeArray == nil) {
        _jokeArray = [NSMutableArray array];
    }
    return _jokeArray;
}

#pragma mark - 内容警告触发方法
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}

@end
